import 'dart:convert';

import 'package:cave_flutter/db_manager/dao/whl_product_dao.dart';
import 'package:floor/floor.dart';
import '../bean/whl_product_bean.dart';

@Database(version: 1, entities: [WhlProductBean])
@TypeConverters([ListStringConverter, CommentModelConverter])
abstract class AppDatabase extends FloorDatabase {
  WhlProductDao get productDao;
}

class ListStringConverter extends TypeConverter<List<String>?, String> {
  @override
  List<String>? decode(String databaseValue) {
    if (databaseValue == 'null' || databaseValue.isEmpty) return null;
    List list = jsonDecode(databaseValue);
    return list.map((e) => e.toString()).toList();
  }

  @override
  String encode(List<String>? value) {
    return jsonEncode(value);
  }
}

class CommentModelConverter extends TypeConverter<List<WhlCommentModel>?, String> {
  @override
  List<WhlCommentModel>? decode(String databaseValue) {
    if (databaseValue == 'null' || databaseValue.isEmpty) return null;
    List list = jsonDecode(databaseValue);
    return list.map((e) => WhlCommentModel.fromJson(e)).toList();
  }

  @override
  String encode(List<WhlCommentModel>? value) {
    return jsonEncode(value);
  }
}
